package com.zhan.signalling.data.listener;

import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.DataListener;
import com.zhan.signalling.check.AccoutPermissionCheck;
import com.zhan.signalling.commons.Constants;
import com.zhan.signalling.commons.SocketEvent;
import com.zhan.signalling.entity.ChatRecord;
import com.zhan.signalling.message.AccoutType;
import com.zhan.signalling.message.Message;
import com.zhan.signalling.message.Result;
import com.zhan.signalling.store.StoreMessageFactory;
import com.zhan.signalling.store.StoreMessageStore;
import com.zhan.signalling.util.RedisUtil;

/**
 * 聊天事件处理
 * @author knight
 *
 */
public class ChatListener implements DataListener<Message> {
	
	private StoreMessageStore dataHandler;
	
	public ChatListener() {
		dataHandler = StoreMessageFactory.getHandler();
		dataHandler.initStore(ChatRecord.class);
	}

	public void onData(SocketIOClient client, Message data, AckRequest ackSender) throws Exception {
		// 校验权限
		AccoutPermissionCheck.check(client, SocketEvent.CHAT_EVENT);
		
		String token = client.get(Constants.USER_TOKEN);
		JSONObject user = client.get(Constants.USER_KEY);
		Integer userRole = client.get(Constants.USER_TYPE);
		String groupId = client.get(Constants.GROUP_KEY);
		String platform = client.getNamespace().getName();
		// 禁言用户
		if(RedisUtil.isForbiddenWord(platform + ":" +groupId, token)) {
			return;
		}
		
		ChatRecord record = new ChatRecord();
		record.setUuId(client.getSessionId().toString());
		record.setContent(data.getContent().toString());
		record.setEventType(SocketEvent.CHAT_EVENT);
		record.setExtras(JSONObject.toJSONString(user));
		record.setGroupId(groupId);
		record.setSendTime(data.getSendTime());
		record.setCreateTime(System.currentTimeMillis());
		record.setPlatform(platform);
		record.setRole(AccoutType.getInstance(userRole).name());
		// 保存消息
		Long seqId = dataHandler.saveChat(record);
		// 存redis
		RedisUtil.addLastSeqId(record.getPlatform_groupId() + ":" + SocketEvent.CHAT_EVENT, seqId);
		// 发送回应
		client.sendEvent(SocketEvent.CHAT_EVENT, 
				new Result("send success", Constants.SUCCESS));
		// 群播消息
		client.getNamespace().getRoomOperations(groupId)
				.sendEvent(SocketEvent.RECEIVE_MESSAGE_EVENT, 
						new Result(record, Constants.SUCCESS));
		
	}

}
